
from os.path import exists

from django import forms
from django.contrib.auth import get_user_model

from .models import *
User = get_user_model()


class UserRegisterForm(forms.Form):
    account = forms.CharField(max_length=20,min_length=2,error_messages={
        'required': "账户不能为空",
        'max_length': "账户字符为2-20个字符",
        'min_length': "账户字符为2-20个字符",
    })
    email = forms.EmailField(error_messages={
        'required': "邮箱不能为空",
        'invalid': "请传入一个正确的邮箱",
    })
    password = forms.CharField(max_length=20,min_length=2,error_messages={
        'required': "密码不能为空",
        'max_length': "密码字符为2-20个字符",
        'min_length': "密码字符为2-20个字符",
    })
    captcha = forms.CharField(max_length=4,min_length=4,error_messages={
        'required': "验证码不能为空",
        'max_length': "验证码为4个数字",
        'min_length': "验证码为4个数字",
    })
    def clean_email(self):
        email = self.cleaned_data['email']
        exist = User.objects.filter(email=email).exists()
        if exist:
            raise forms.ValidationError("邮箱已注册,请更换邮箱注册")
        return email
    def clean_captcha(self):
        input_captcha = self.cleaned_data['captcha']
        tmp = CaptchaIdentify.objects.get(email=self.cleaned_data['email'])
        captcha = tmp.captcha
        if input_captcha != captcha:
            raise forms.ValidationError("验证码不正确")
        return input_captcha

class UserLoginForm(forms.Form):
    account = forms.CharField(max_length=20,min_length=2,error_messages={
        'required': "账户不能为空",
        'max_length': "账户字符为2-20个字符",
        'min_length': "账户字符为2-20个字符",
    })
    password = forms.CharField(max_length=20,min_length=2,error_messages={
        'required': "密码不能为空",
        'max_length': "密码字符为2-20个字符",
        'min_length': "密码字符为2-20个字符",
    })
    checked = forms.BooleanField(required=False)

class UserIconForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('icon',)
    def clean_icon(self):
        icon = self.cleaned_data['icon']
        if icon.size > 5 * 1024 * 1024:
            raise forms.ValidationError("图片大小不能超过5MB")
        return icon

"""
 def __init__(self, *args, **kwargs):
        self.instance = kwargs.pop('instance', None)  # 提取 instance
        super().__init__(*args, **kwargs)
        if self.instance:  # 如果传入了实例，填充初始值
            self.fields['avatar'].initial = self.instance.avatar
            self.fields['bio'].initial = self.instance.bio

    # 手动保存数据到模型
    def save(self):
        if self.instance:
            # 更新现有实例
            self.instance.avatar = self.cleaned_data['avatar']
            self.instance.bio = self.cleaned_data['bio']
            self.instance.save()
            return self.instance
        else:
            # 创建新实例（如果需要）
            return Profile.objects.create(**self.cleaned_data)
"""